//
//  JQTabBar.swift
//  sinaWeibo
//
//  Created by maoge on 16/4/16.
//  Copyright © 2016年 maoge. All rights reserved.
//

import UIKit

class JQTabBar: UITabBar {
    
    //设置点击按钮闭包
    var composeButtonClosure:(() -> ())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        addSubview(composeButton)
    }

    private lazy var composeButton: UIButton = {
        let btn = UIButton()
        
        //监听按钮点击
        btn.addTarget(self, action: "composeButtonClick", forControlEvents: .TouchUpInside)
        
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        
        //内容多大, 控件就多大
        btn.sizeToFit()
        
        return btn
    }()
    
    //MARK: - 监听方法
    @objc private func composeButtonClick(){
        composeButtonClosure?()
    }

    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        composeButton.center = CGPoint(x: self.frame.width * 0.5, y: self.frame.height * 0.5)
        
        let childWidth = frame.size.width / 5
        
        var index = 0
        
        for childView in subviews {
            
            //如果当前遍历的View是UITabBarButton
            if childView.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                //设置按钮的宽
                childView.frame.size.width = childWidth
                childView.frame.origin.x = CGFloat(index) * childWidth
                
                //index递增
                index++;
                
                //如果当前遍历到'发现'，则把发现往后移动一个位置
                if index == 2 {
                    index++
                }
                
            }
        }
    }
}
